<%@ page import="java.util.*,java.sql.*,org.owasp.esapi.ESAPI" pageEncoding="UTF-8" buffer="1000kb" contentType="text/html; charset=UTF-8" %><jsp:useBean id="readingsManager" scope="application" class="org.languageguide.readings.ReadingManager" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<%
	//String translationString = code.getTranslationString(category, lang, langTrans);
	
	org.languageguide.user.User user = org.languageguide.user.UserManager.getUser(session);
	if (user == null){
		user =	org.languageguide.user.UserManager.loginFromCookie(request);
		if (user == null){
			response.sendRedirect("/user/login.jsp");
			return;
		}
	}
	String submit = request.getParameter("translation.submit");
	if (submit == null){
		submit = "Save";
	}


	request.setCharacterEncoding("UTF-8");
		String target = request.getParameter("target");


	//org.languageguide.translation.Category cat = categoryManager.getCategory(category, num, language, target);
	if (submit.equals("Cancel")){
		//cat.finishEdit();
		//user.unlockCategories();
		//
		//redirect(categoryManager, response, request, category, num, language, target, section);
		response.sendRedirect(".?language=en&target=" + target);
		return;

	}

//readingsManager.saveTranslations(session, request, user);
		String totalStr  = request.getParameter("row_count");
		//System.out.println("totalStr" + totalStr);
		int total = Integer.parseInt(totalStr);
		String readingId = request.getParameter("readingId");

		if (readingId == null || totalStr == null || target == null){
			System.out.println("error");
			//return ;
		}
		String message = null;
	
		org.languageguide.storage.DBConnector connector = org.languageguide.storage.DBConnector.getInstance();
		java.sql.Connection connection = connector.getConnection();	
		
		Map<Integer, Integer> translationIdMap = new TreeMap<Integer, Integer>();
		Map<Integer, String> translationMap = new TreeMap<Integer, String>();
		try{
			
			//String getReadingSql = "SELECT Id, SentenceOrder,  LEFT JOIN ReadingSentenceTranslations ON ReadingSentenceTranslations.ReadingSentencesId = ReadingSentences.Id FROM ReadingSentences where ReadingId = ?";	
			String getReadingSql = "SELECT ReadingSentences.Id, ReadingSentences.SentenceOrder, ReadingSentenceTranslations.Translation FROM ReadingSentences LEFT JOIN ReadingSentenceTranslations ON ReadingSentenceTranslations.ReadingSentencesId = ReadingSentences.Id AND ReadingSentenceTranslations.TargetLanguage = ? WHERE ReadingId = ?";
			PreparedStatement stmt = connection.prepareStatement(getReadingSql);
			stmt.setString(1, target);
			stmt.setString(2, readingId);
			ResultSet rs = stmt.executeQuery();
			while (rs.next()){
				Integer translationId = rs.getInt(1);
				Integer sentenceOrder = rs.getInt(2);
				String translation = rs.getString(3);
				translationIdMap.put(sentenceOrder, translationId);
				translationMap.put(sentenceOrder, translation);
			}
			
			String sql_save = "INSERT INTO ReadingSentenceTranslations (ReadingSentencesId, TargetLanguage, Translation) Values (?, ?, ?)";
			String sql_update = "UPDATE ReadingSentenceTranslations Set Translation = ? WHERE ReadingSentencesId = ? AND TargetLanguage  = ?";
			connection.setAutoCommit(false);
			 stmt = connection.prepareStatement(sql_save);
			 PreparedStatement stmtUpdate = connection.prepareStatement(sql_update);
			String ipAddress = request.getRemoteAddr();
			
			for (int parameterId = 1; parameterId <= total; parameterId++){
				String param = request.getParameter("" + parameterId);
				param = ESAPI.encoder().encodeForHTML(param);
				System.out.println("parameterId" + parameterId + " " + param + "<br/>");
				if (param != null){
					//Integer paramInt = Integer.parseInt(param);
					Integer readingSentenceId = translationIdMap.get(parameterId);
					String translation = translationMap.get(parameterId);
					System.out.println("translation" + translation + "-" + param);
					if (translation == null){
						stmt.setInt(1, readingSentenceId);
						stmt.setString(2, target);
						stmt.setString(3, param);
						stmt.addBatch();
					}
					else if (!param.equals(translation)){
						System.out.println("update" + param + "-" + translation);
						stmtUpdate.setString(1, param);
						stmtUpdate.setInt(2, readingSentenceId);
						stmtUpdate.setString(3, target);						
						stmtUpdate.addBatch();
					}
					//reading.saveSentenceTranslation(connection, parameterId, param, user, ipAddress);				
				}
					//String approvalvalue = request.getParameter("approval" + parameterId);

					//System.out.println("param:" + param);			
					//if (param.indexOf("&#x3f;") == -1) // some browsers are putting weird stuff in translation



					//			parameterId++;
				//		else{
				//		parametersExist = false;
				//}
			}
			stmt.executeBatch();
			stmtUpdate.executeBatch();
			connection.commit();
			//cat.prepare();
			//cat.finishEdit();
		//	user.unlockCategories();
	
	
	org.languageguide.readings.ApprovalUtil.setApproval(request, connection, readingId, target, "ApprovedSentences");
			session.setAttribute("message", "Thank you! Your translations have been saved.");
			//redirect(categoryManager, response, request, category, num, language, target, section);
			
			response.sendRedirect(".?language=en&target=" + target);
		}
		catch (java.sql.SQLException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			final java.io.Writer result = new java.io.StringWriter();
		    final java.io.PrintWriter printWriter = new java.io.PrintWriter(result);
	    	e.printStackTrace(printWriter);
			message = e.getMessage();
			message += e.getCause();
			message += "<br />";
			message += result;
			System.out.println("translation save failure:" + message);
		} 
		finally{
//			cat.cleanUpStatements();
			if (connector != null){
				connector.close(connection);
			}
		}
	//String error = "An error occurred while saving the translations: " + message;
%>
<strong>done</strong>
</body>
</html></em>